﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ARS.Common.Helper
{
    public class StringHelper
    { /// <summary>
      /// 使用MD5加密算法加密字符串
      /// </summary>
      /// <param name="quondamText">明文</param>
      /// <returns>密文</returns>
        public static string MD5(string quondamText = "")
        {
            if (string.IsNullOrEmpty(quondamText))
            {
                quondamText = "";
            }
            var hashAlgorithm = System.Security.Cryptography.MD5.Create("md5");
            byte[] data = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(quondamText));
            return BytesToString(data);
        }
        /// <summary>
        /// 字节转换为字符串
        /// </summary>
        /// <param name="bytes">字符</param>
        /// <returns>字符串</returns>
        public static string BytesToString(byte[] bytes)
        {
            var sBuilder = new StringBuilder();
            foreach (byte bit in bytes)
            {
                sBuilder.Append(bit.ToString("X2"));
            }
            return sBuilder.ToString();
        }
        /// <summary>
        /// 验证MD5加密算法加密的字符串是否为指定明文的加密结果
        /// </summary>
        /// <param name="quondamText">明文</param>
        /// <param name="cryptographText">密文</param>
        /// <returns></returns>
        public static bool ValidateByMD5(string quondamText, string cryptographText)
        {
            string cipherText = MD5(quondamText);
            return (cipherText == cryptographText);
        }

        public static string GetMD5(IEnumerable<string> data, bool isLower = true)
        {
            var result = MD5(string.Join("", data));
            if (isLower)
                return result.ToLower();
            return result;
        }
        public static string KeyBase64 = "encodeBase+10240";//数据通信加密公钥	
        /// <summary>
        /// Matchs
        /// </summary>
        /// <param name="text"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static MatchCollection Matchs(string text, string pattern)
        {
            Regex regex;

            MatchCollection matchs;

            try
            {
                regex = new Regex(pattern, RegexOptions.IgnoreCase);

                matchs = regex.Matches(text);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return matchs;
        }


        /// <summary>
        /// 是否包含中文
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool isChinese(string c)
        {
            //是否包含中文
            System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex(@"[\u4e00-\u9fa5]");
            return Regex.IsMatch(c);
        }


        /// <summary>
        /// 是否日期
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsDate(string c)
        {
            //是否是日期
            return false;
            // return Microsoft.VisualBasic.Information.IsDate(c);
        }

        /// <summary>
        ///  加密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Encrypt(string text, string password = "merlinking")
        {
            if (string.IsNullOrEmpty(text))
            {
                return "";
            }
            RijndaelManaged rijndaelCipher = new RijndaelManaged
            {
                Mode = CipherMode.ECB,

                Padding = PaddingMode.Zeros,

                KeySize = 128,

                BlockSize = 128
            };

            byte[] pwdBytes = Encoding.UTF8.GetBytes(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            rijndaelCipher.IV = keyBytes;

            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

            byte[] plainText = Encoding.UTF8.GetBytes(text);

            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            return Convert.ToBase64String(cipherBytes);

        }
        /// <summary>
        ///  解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string DeEncrypt(string text, string password = "merlinking")
        {
            if (string.IsNullOrEmpty(text))
            {
                return "";
            }
            try
            {
                RijndaelManaged rijndaelCipher = new RijndaelManaged
                {
                    Mode = CipherMode.ECB,

                    Padding = PaddingMode.Zeros,

                    KeySize = 128,

                    BlockSize = 128
                };

                byte[] encryptedData = Convert.FromBase64String(text);

                byte[] pwdBytes = Encoding.UTF8.GetBytes(password);

                byte[] keyBytes = new byte[16];

                int len = pwdBytes.Length;

                if (len > keyBytes.Length) len = keyBytes.Length;

                System.Array.Copy(pwdBytes, keyBytes, len);

                rijndaelCipher.Key = keyBytes;

                rijndaelCipher.IV = keyBytes;

                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

                byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

                return Encoding.UTF8.GetString(plainText);
            }
            catch
            {
                return "";
            }

        }

        /// <summary>
        ///把数组拼成字符串
        /// </summary>
        /// <param name="Arr"></param>
        /// <returns></returns>
        public static string JoinArray(IList<string> Arrays)
        {
            StringBuilder strbu = new StringBuilder();
            foreach (string str in Arrays)
            {
                strbu.Append(str + ",");
            }
            if (strbu.Length > 1)
            {
                strbu.Remove(strbu.Length - 1, 1);
            }
            return strbu.ToString();

        }
        /// <summary>
        ///把数组拼成字符串
        /// </summary>
        /// <param name="Arr"></param>
        /// <returns></returns>
        public static string JoinArray(int[] Arrays)
        {
            StringBuilder strbu = new StringBuilder();
            foreach (int str in Arrays)
            {
                strbu.Append(str + ",");
            }
            if (strbu.Length > 1)
            {
                strbu.Remove(strbu.Length - 1, 1);
            }
            return strbu.ToString();


        }


        /// <summary>
        ///把数组拼成字符串
        /// </summary>
        /// <param name="Arrays"></param>
        /// <returns></returns>
        public static string JoinArray(string[] Arrays)
        {
            StringBuilder strbu = new StringBuilder();
            foreach (string str in Arrays)
            {
                strbu.Append(str + ",");
            }
            if (strbu.Length > 1)
            {
                strbu.Remove(strbu.Length - 1, 1);
            }
            return strbu.ToString();
        }

        public static bool IsNumeric(string c)
        {
            return false;
            //  return Microsoft.VisualBasic.Information.IsNumeric(c);
        }

        /// <summary>
        /// Matchs
        /// </summary>
        /// <param name="text"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static Match Match(string text, string pattern)
        {
            Regex regex;

            Match match;

            try
            {
                regex = new Regex(pattern, RegexOptions.IgnoreCase);

                match = regex.Match(text);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return match;
        }

        /// <summary>
        /// Replace
        /// </summary>
        /// <param name="text"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static string Replace(string text, string pattern, string replaceMent)
        {
            Regex regex;

            string match;

            try
            {
                regex = new Regex(pattern, RegexOptions.IgnoreCase);

                match = regex.Replace(text, replaceMent);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return match;
        }

        #region 方法，去掉所有HTML标签
        /// <summary>
        /// 方法，去掉所有HTML标签
        /// </summary>
        /// <param name="htmlText">含HTML标签的文本</param>
        /// <returns></returns>
        public static string ClearHtmlTags(string htmlText)
        {
            System.Text.RegularExpressions.Regex rx = new Regex(@"<[\s\S]*?>");

            MatchCollection matches = rx.Matches(htmlText);

            foreach (Match match in matches)
            {
                htmlText = htmlText.Replace(match.Value, string.Empty);
            }

            return htmlText;
        }
        #endregion


        /// <summary>
        /// 读取任意字符串的ASCII码，在地址栏传参数时用到。
        /// </summary>
        /// <param name="words"></param>
        /// <returns></returns>
        public static string GetASCII(string words)
        {
            if (words == null || words == string.Empty)
                return string.Empty;

            StringBuilder strbu = new StringBuilder();
            foreach (char word in words)
            {
                strbu.AppendFormat("%u{0}", Convert.ToString((short)word, 16));
            }

            return strbu.ToString();
        }
        /// <summary>
        /// 读取字符串分隔的最后一部分，如aaa/bbb/ccc/ddd.jpg得到jpg
        /// </summary>
        /// <param name="words"></param>
        /// <param name="spritor"></param>
        /// <returns></returns>
        public static string GetLast(string words, string spritor)
        {
            string[] tempStringArray = words.Split(spritor.ToCharArray());
            string re = "";
            if (tempStringArray.Length > 0)
            {
                re = tempStringArray[tempStringArray.Length - 1];
            }
            return re;
        }

        public static int GetKeyByParam(string param)
        {
            int re = 0;
            string str = StringHelper.GetKeyByParam(param, "HDID");
            if (StringHelper.IsNumeric(str))
            {
                re = Convert.ToInt32(str);
            }
            return re;
        }
        public static string GetKeyByParam(string param, string Key)
        {
            if (param.Length == 0)
            {
                return string.Empty;
            }
            string Value = StringHelper.DeEncrypt(param, StringHelper.KeyBase64);
            Key = Key + "=";
            int index = Value.IndexOf(Key);
            if (index >= 0)
            {

                Value = Value.Substring(index);
                Value = Value.Split("|".ToCharArray())[0];
                Value = Value.Replace(Key, "");

            }

            return Value;

        }
        /// <summary>
        /// 移出最后一个逗号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string removeComma(string str)
        {
            if (str.IndexOf(",") >= 0)
            {
                if (str.LastIndexOf(",") == str.Length - 1)
                {
                    str = str.Substring(0, str.Length - 1);
                }
            }
            return str;
        }
        public static string MakeNumStr(int input, int num)
        {
            string re = "";
            num = Convert.ToInt32(Math.Pow(10, (double)num));
            num = num + input;
            re += num;
            re = re.Remove(0, 1);
            return re;
        }

        /// <summary> Tags 关键字的分隔符处理 将传入的字符串中的分隔符统一替换为所需的字符。并去除首尾符号</summary>
        /// <author>JIANG,ZHIMING</author>
        /// <version>V1.0</version>
        /// <example>"在，你；心中 我，，"替换为 ","</example>
        /// <param name="tags">要进行分隔符替换的字符串</param>
        /// <param name="separator">要替换为的字符</param>
        /// <returns></returns>
        public static string TagsSeparatorHandle(string tags, string separator)
        {
            // Regex search and replace
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(@"，|\s|;|；", options);
            string result = regex.Replace(tags, separator);

            //移除首尾符号
            while (result.IndexOf(",") == 0 && result != "")
            {
                result = result.Substring(1, result.Length);
            }
            while (result.LastIndexOf(",") == result.Length - 1 && result != "")
            {
                result = result.Substring(0, result.Length - 1);
            }

            return result;
        }

        public static string CheckSQLSecurity(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                //单引号替换成两个单引号
                input = input.Replace("'", "''");
            }

            return input;
        }

        /// <summary>
        /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
        /// </summary>
        /// <param name="p_SrcString">要检查的字符串</param>
        /// <param name="p_Length">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
        {
            if (p_SrcString == null)
                return "";

            string myResult = p_SrcString;

            if (p_Length >= 0)
            {
                byte[] bsSrcString = System.Text.Encoding.Default.GetBytes(p_SrcString);

                if (bsSrcString.Length > p_Length)
                {
                    int nRealLength = p_Length;
                    int[] anResultFlag = new int[p_Length];
                    byte[] bsResult = null;

                    int nFlag = 0;
                    for (int i = 0; i < p_Length; i++)
                    {

                        if (bsSrcString[i] > 127)
                        {
                            nFlag++;
                            if (nFlag == 3)
                            {
                                nFlag = 1;
                            }
                        }
                        else
                        {
                            nFlag = 0;
                        }

                        anResultFlag[i] = nFlag;
                    }

                    if ((bsSrcString[p_Length - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
                    {
                        nRealLength = p_Length + 1;
                    }

                    bsResult = new byte[nRealLength];

                    Array.Copy(bsSrcString, bsResult, nRealLength);

                    myResult = System.Text.Encoding.Default.GetString(bsResult);

                    myResult = myResult + p_TailString;
                }

            }

            return myResult;
        }


        /// <summary>
        /// 检测字符串是否是以空白字符开始的
        /// </summary>
        public static bool IsStartWidthBlankChar(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }

            Regex r = new Regex(@"^\s.*", RegexOptions.Compiled);

            return r.IsMatch(str);
        }

        /// <summary>
        /// 判断字符串是否是数字的集合，数字之间使用英文逗号（","）分隔
        /// </summary>
        /// <param name="numString"></param>
        /// <returns></returns>
        public static bool IsNumericCollectionString(string numString)
        {
            if (string.IsNullOrEmpty(numString))
            {
                return false;
            }

            Regex r = new Regex(@"^\d+(,\d+)*$", RegexOptions.Compiled);

            return r.IsMatch(numString);
        }

        /// <summary>
        /// 计算字符串长度
        /// </summary>
        public static string GetStringSize(string str)
        {
            return Encoding.GetEncoding("utf-8").GetByteCount(str).ToString();
            //return Math.Round(Encoding.GetEncoding("utf-8").GetByteCount(str) / 1024f, MidpointRounding.ToEven) + "KB";
        }

        public static string FormatStringToXmlString(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }

            string result = str.Replace("&", "&amp;");

            result = result.Replace("<", "&lt;");
            result = result.Replace(">", "&gt;");
            result = result.Replace("'", "&apos;");
            result = result.Replace("\"", "&quot;");

            return result;
        }

        public static string GetArrayStr(IEnumerable list, string speater)
        {
            StringBuilder sb = new StringBuilder();

            foreach (object obj in list)
            {
                sb.Append(speater);
                sb.Append(obj.ToString());
            }

            if (sb.Length != 0)
            {
                return sb.ToString().Substring(speater.Length);
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// 使用反射把List<T>转换成Json
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="jsonName">Json的名字</param>
        /// <param name="IL">List<T>duixiang</param>
        /// <returns></returns>
        public static string ObjectToJson<T>(string jsonName, IList<T> IL)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + jsonName + "\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        public static bool isID(string str)
        {
            string p = @"^[1-9](\d{13}|\d{16})[a-zA-Z0-9]$";//@"^([1-9]\d{5}((19|20)[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01]))\d{3}[a-zA-Z0-9])$";
            Regex r = new Regex(p, RegexOptions.IgnoreCase);
            Match m = r.Match(str);
            return m.Success;
        }

        /// <summary>
        /// 验证身份证号码是否正确,18位身份证号 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public static bool isEffectiveID(string id)
        {
            try
            {
                if (id.Length == 15) return true;//15位没有算法，需根据身份证含义进行匹配验证，此处暂为true
                if (isID(id))
                {
                    int idS = 0;
                    int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
                    char[] iN = id.ToCharArray();
                    string LastCode = "10X98765432";
                    for (int i = 0; i < 17; i++)
                    {
                        int y = Convert.ToInt32(iN[i].ToString());
                        idS += y * iW[i];
                    }
                    int iY = idS % 11;
                    return id.Substring(0, 17) + LastCode.Substring(iY, 1).ToUpper() == id.ToUpper();
                }
                else
                {
                    return false;
                }
            }
            catch { return false; }

        }








        /// <summary>
        /// 生成随机位数的字符串
        /// </summary>
        /// <param name="Median">随机的位数</param>
        /// <returns></returns>
        public static string Getcode(int Median)
        {
            string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string code = "";
            string[] strArr = so.Split(',');
            Random rand = new Random();
            for (int i = 0; i < Median; i++)
            {
                code += strArr[rand.Next(0, strArr.Length)];
            }

            return code.ToUpper();
        }
        /// <summary>
        /// 生成随机位数的字符串
        /// </summary>
        /// <param name="Median">随机的位数</param>
        /// <param name="IsDigital">是否是数字</param>
        /// <returns></returns>
        public static string Getcode(int Median, bool IsDigital = false)
        {
            string so;
            if (IsDigital)
            {
                so = "1,2,3,4,5,6,7,8,9,0";
            }
            else
            {
                so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,j,k,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            }
            string code = "";
            string[] strArr = so.Split(',');
            Random rand = new Random();
            for (int i = 0; i < Median; i++)
            {
                code += strArr[rand.Next(0, strArr.Length)];
            }

            return code.ToUpper();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTable2Json(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            if (dt == null || dt.Rows.Count == 0)
            {
                return "[]";
            }
            sb.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sb.Append(dt.Columns[j].ColumnName);
                    sb.Append(":\"");
                    sb.Append(dt.Rows[i][j].ToString());
                    sb.Append("\",");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }



        /// <summary>
        /// 把特定字符替换为* 用来隐藏隐私信息
        /// </summary>
        /// <param name="Str">原始字符串</param>
        /// <param name="Start">开始位置</param>
        /// <param name="End">个数</param>
        /// <param name="Character">要替换的字符</param>
        /// <returns></returns>
        public static string TxtReplace(string Str, int Start, int End, char Character)
        {
            string EndStr = string.Empty;
            if (Str.Length > Start + End)
            {
                string a = string.Empty;
                int i = Start + End;
                while (i > 0) { a += Character; i--; }
                EndStr = Str.Replace(Str.Substring(Start, End), a);
            }
            else
            {
                EndStr = Str;
            }
            return EndStr;
        }


        /// <summary>
        /// 把特定字符替换为* 用来隐藏隐私信息
        /// </summary>
        /// <param name="Str">原始字符串</param>
        /// <param name="Start">开始位置</param>
        /// <param name="End">个数</param>
        /// <param name="Character">要替换的字符</param>
        /// <returns></returns>
        public static string TxtReplace_New(string Str, int Start, int End, string Character)
        {
            string EndStr = string.Empty;
            if (Str.Length > Start + End)
            {
                string a = string.Empty;
                int i = End;
                while (i > 0) { a += Character; i--; }
                EndStr = Str.Replace(Str.Substring(Start, End), a);
            }
            else
            {
                EndStr = Str;
            }
            return EndStr;
        }



        /// <summary>
        /// 加密字符串 数据换码加解密
        /// </summary>
        /// <param name="content">待加密的数据</param>
        /// <param name="vectorSeed">跳码 不允许重复</param>
        /// <returns></returns>
        public static string EncryptInvert(string content, uint[] vectorSeed)
        {
            if (string.IsNullOrEmpty(content) || vectorSeed.Length <= 0 || content.Length <= vectorSeed.Length)
                throw new Exception("字符串为空,无法加解密");
            
            var cts = content.Length-1;
            char[] tempChar = content.ToCharArray();
            foreach (var info in vectorSeed)
            {
                char m= tempChar[info];
                tempChar[info] = tempChar[cts - info];
                tempChar[cts - info] = m;
            }
            return string.Join("", tempChar);
        }
        /// <summary>
        /// 解密字符串 数据换码加解密
        /// </summary>
        /// <param name="content">待加密的数据</param>
        /// <param name="vectorSeed">跳码 不允许重复</param>
        /// <returns></returns>
        public static string DecryptInvert(string content, uint[] vectorSeed)
        {
            if (string.IsNullOrEmpty(content) || vectorSeed.Length <= 0 || content.Length <= vectorSeed.Length)
                throw new Exception("字符串为空,无法加解密");

            var cts = content.Length - 1;
            char[] tempChar = content.ToCharArray();
            foreach (var info in vectorSeed)
            {
                //char m = tempChar[info];
                //tempChar[info] = tempChar[cts - info];
                //tempChar[cts - info] = m;
                char m = tempChar[cts - info];
                tempChar[cts - info]=tempChar[info];
                tempChar[info]= m;
            }
            return string.Join("", tempChar);
        }

        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length); stream.Flush(); stream.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            { throw new Exception("序列化失败,原因:" + ex.Message); }
        }
        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T Desrialize<T>(string str)
        {
            T obj = default(T);
            try
            {
                IFormatter formatter = new BinaryFormatter();
                byte[] buffer = Convert.FromBase64String(str);
                MemoryStream stream = new MemoryStream(buffer);
                obj = (T)formatter.Deserialize(stream); stream.Flush();
                stream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("反序列化失败,原因:" + ex.Message);
            }
            return obj;
        }




    }

}
